<template>
  <div class="page-giveaway-add-or-update">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{
          dataForm.giveawayId
            ? (pageType === 1 ? $t('giveaway.editGiveaway') : $t('giveaway.viewGiveaway'))
            : $t('giveaway.addGiveaway')
        }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      class="form-box"
      label-width="auto"
      @submit.prevent
    >
      <!--套餐名称-->
      <el-form-item
        :label="$t('group.actName')"
        prop="name"
      >
        <el-input
          v-model="dataForm.name"
          :disabled="pageType === 2"
          maxlength="20"
          show-word-limit
          class="coupon-input"
          :placeholder="$t('group.actName')"
          style="width:526px"
        />
      </el-form-item>
      <!--活动时间-->
      <el-form-item
        :label="$t('marketing.activTime') + ':'"
        :required="true"
      >
        <div class="date-picker">
          <!--开始时间-->
          <el-form-item prop="startTime">
            <el-date-picker
              v-model="dataForm.startTime"
              :disabled="pageType === 2"
              type="date"
              :placeholder="$t('live.chooseStartDate')"
              value-format="YYYY-MM-DD"
              style="width:140px"
            />
            <el-time-select
              v-model="startTimeValue"
              start="00:00"
              step="00:30"
              end="23:30"
              :class="[startTimeValue ? 'select-time': '']"
              style="width:106px"
              :disabled="pageType === 2"
              :placeholder="$t('time.startTime')"
            />
          </el-form-item>
          <span style="margin: 0 10px">{{ $t('time.tip') }}</span>
          <!--结束时间-->
          <el-form-item prop="endTime">
            <el-date-picker
              v-model="dataForm.endTime"
              :disabled="pageType === 2"
              type="date"
              :placeholder="$t('live.chooseEndDate')"
              value-format="YYYY-MM-DD"
              style="width:140px"
            />
            <el-time-select
              v-model="endTimeValue"
              start="00:00"
              step="00:30"
              end="23:30"
              :class="[endTimeValue ? 'select-time': '']"
              style="width:106px"
              :disabled="pageType === 2"
              :placeholder="$t('time.startTime')"
            />
          </el-form-item>
        </div>
      </el-form-item>
      <!--套餐主商品-->
      <el-form-item
        :label="$t('giveaway.giveawayMainProd')"
        :required="true"
        style="width: 100%;"
      >
        <div
          v-if="dataForm.prodId != null"
          class="prodItem-table"
        >
          <el-table
            :data="[dataForm]"
            header-cell-class-name="table-header"
            row-class-name="table-row"
            :style="{ width: dataForm.status ? '820px' : '680px' }"
          >
            <el-table-column
              :label="$t('group.prodInfo')"
              prop="reason"
              fixed="left"
              align="center"
              width="320px"
            >
              <template #default="scope">
                <div class="prod-info-container">
                  <div class="prod-image">
                    <prod-pic :pic="scope.row.pic" />
                  </div>
                  <div class="prod-name">
                    <div class="prod-name-txt">
                      {{ scope.row.prodName }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('product.price')"
              align="center"
              prop="price"
              width="200px"
            />
            <el-table-column
              prop="giveawayNum"
              :label="$t('giveaway.buyNum')"
              align="center"
              width="160px"
            >
              <template #header>
                {{ $t('giveaway.buyNum') }}
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="$t('giveaway.buyNumTips')"
                  placement="top"
                >
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </template>
              <template #default="scope">
                <div class="custom-rate">
                  <input
                    v-model="scope.row.buyNum"
                    :disabled="pageType === 2"
                    type="number"
                    :precision="0"
                    :min="1"
                    :max="99999999"
                    :step="1"
                    style="width: 80%;"
                    class="tag-input-width"
                    @keydown="restrictedInput"
                    @keyup="
                      scope.row.buyNum = String(scope.row.buyNum).match(/[^0-9]/) ? 1 : scope.row.buyNum
                    "
                    @blur="inputBuyNum(scope.row.buyNum, 1, 99999999)"
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="dataForm.status"
              align="center"
              :label="$t('crud.menu')"
              fixed="right"
              width="140px"
            >
              <template #default>
                <!-- <div v-if="dataForm.status" class="text-btn-con"> -->
                <div
                  v-if="dataForm.status"
                  class="text-btn-con"
                >
                  <div
                    class="default-btn text-btn"
                    @click="deleteMainProd"
                  >
                    {{ $t('text.delBtn') }}
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="dataForm.prodId == null">
          <div
            :class="['default-btn']"
            @click="addProd"
          >
            {{ $t("product.select") }}
          </div>
        </div>
        <div
          v-if="!verifyProdFlag"
          class="error-tips"
        >
          {{ $t('giveaway.mainProdErrorTips') }}
        </div>
      </el-form-item>
      <!--套餐搭配商品-->
      <el-form-item
        :label="$t('giveaway.giveawayMatchingProd')"
        :required="true"
      >
        <!--搭配商品表格-->
        <giveawayProdTable
          ref="giveAwayProdTableRef"
          :page-type="pageType"
          :type="2"
          :limit="15"
        />
      </el-form-item>
      <el-form-item :label="' '">
        <div
          class="default-btn"
          @click="back()"
        >
          {{
            $t("shopFeature.edit.back")
          }}
        </div>
        <div
          v-if="pageType === 1"
          class="default-btn primary-btn"
          @click="dataFormSubmit()"
        >
          {{
            $t("crud.filter.submitBtn")
          }}
        </div>
      </el-form-item>
    </el-form>
    <!-- 主商品选择弹窗-->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :is-single="true"
      :giveaway-id="dataForm.giveawayId"
      data-url="/shop/giveawayProd/mainProdPage"
      @refresh-select-prods="selectMainProd"
    />
  </div>
</template>

<script setup>
import giveawayProdTable from './components/prod-table.vue'

import { onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const Data = reactive({
  dataForm: {
    giveawayId: 0,
    name: '',
    startTime: '',
    endTime: '',
    prodId: null,
    pic: null,
    prodName: null,
    giveawayProds: []
  },
  pageType: 1, // 1：新增/编辑 2：查看
  verifyProdFlag: true, // 主商品校验标志
  mainSkuIds: [], // 主商品skuId列表
  matchingSkuIds: [], // 搭配商品skuId列表
  page: {
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
  },
  errorTip: false,
  dataListSelections: [],
  prodsSelectVisible: false,
  startTimeValue: '',
  endTimeValue: ''
})
const { dataForm, pageType, verifyProdFlag, prodsSelectVisible, startTimeValue, endTimeValue } = toRefs(Data)

const validName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('seckill.evenBeEmpty')))
  } else {
    callback()
  }
}
const validateTime = (rule, value, callback) => {
  const startTime = Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00'
  const endTime = Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00'
  if (rule.field === 'startTime' && (!Data.startTimeValue || !Data.dataForm.startTime)) {
    callback(new Error($t('formData.startTimeCannotBeEmpty')))
  }
  if (rule.field === 'endTime' && (!Data.endTimeValue || !Data.dataForm.endTime)) {
    callback(new Error($t('formData.endTimeCannotBeEmpty')))
  }
  if (rule.field === 'startTime' && Date.parse(startTime) >= Date.parse(endTime)) {
    callback(new Error($t('marketing.timeCanThanOrEqualTo')))
  }
  if ((Data.dataForm.giveawayId === 0 || Data.dataForm.status === 1) && rule.field === 'endTime' && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  } else {
    callback()
  }
}

const dataRule = reactive({
  name: [
    { required: true, message: $t('seckill.evenBeEmpty'), trigger: 'blur' },
    { validator: validName, trigger: 'blur' }
  ],
  activityDate: [
    { required: true, message: $t('shop.titCanNoBlank'), trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('formData.startTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('formData.endTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateTime, trigger: 'blur' }
  ]
})

const route = useRoute()
const commonStore = useCommonStore()
onMounted(() => {
  const giveawayId = Number(route.query.giveawayId) ? Number(route.query.giveawayId) : 0
  const pageType = route.query.pageType ? route.query.pageType : 1
  init(giveawayId)
  Data.pageType = parseInt(pageType || 0)
  const title = giveawayId ? (Data.pageType === 1 ? $t('giveaway.editGiveaway') : $t('giveaway.viewGiveaway')) : $t('giveaway.addGiveaway')
  commonStore.replaceSelectMenu(title)
})

const dataFormRef = ref()
// 获取数据列表
const init = (giveawayId) => {
  Data.dataForm.giveawayId = Number(giveawayId) || 0
  nextTick(() => {
    dataFormRef.value.resetFields()
    const datetimeRange = getDateTimeRange()
    Data.dataForm.startTime = datetimeRange.startTime
    Data.dataForm.endTime = datetimeRange.endTime
    Data.startTimeValue = datetimeRange.currentTime
    Data.endTimeValue = datetimeRange.currentTime
    if (Data.dataForm.giveawayId && Data.dataForm.giveawayId !== '0') {
      getDataInfo()
    }
  })
}

const giveAwayProdTableRef = ref()
// 获取套餐信息
const getDataInfo = () => {
  http({
    url: http.adornUrl(`/shop/giveaway/info/${Data.dataForm.giveawayId}`),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    Data.dataForm = data
    Data.startTimeValue = Data.dataForm.startTime ? Data.dataForm.startTime.substring(11, Data.dataForm.startTime.length - 3) : ''
    Data.endTimeValue = Data.dataForm.endTime ? Data.dataForm.endTime.substring(11, Data.dataForm.endTime.length - 3) : ''
    Data.dataForm.startTime = getParseTime(Data.dataForm.startTime, '{y}-{m}-{d}')
    Data.dataForm.endTime = getParseTime(Data.dataForm.endTime, '{y}-{m}-{d}')
    giveAwayProdTableRef.value.init(data.giveawayProds)
  })
}

// 主商品选择更新回调
const selectMainProd = (prodItems) => {
  const prodObj = prodItems
  if (prodObj) {
    Data.dataForm.prodId = prodObj.prodId
    Data.dataForm.pic = prodObj.pic
    Data.dataForm.prodName = prodObj.prodName
    Data.dataForm.price = prodObj.price
    Data.dataForm.buyNum = 1
    Data.verifyProdFlag = true
    Data.dataForm.status = 1
  }
}

// 表单提交
const dataFormSubmit = () => {
  if (Data.isSubmit) {
    return
  }
  Data.isSubmit = true
  dataFormRef.value.validate((valid) => {
    const giveawayProds = giveAwayProdTableRef.value.verifyDataForm()
    if (!Data.dataForm.prodId) {
      Data.verifyProdFlag = false
      Data.isSubmit = false
      return
    }
    if (!giveawayProds) {
      Data.isSubmit = false
      return
    }
    if (valid) {
      const startTime = Data.dataForm.startTime
      const endTime = Data.dataForm.endTime
      Data.dataForm.startTime = Data.dataForm.startTime && Data.startTimeValue ? Data.dataForm.startTime + ' ' + Data.startTimeValue + ':00' : ''
      Data.dataForm.endTime = Data.dataForm.endTime && Data.endTimeValue ? Data.dataForm.endTime + ' ' + Data.endTimeValue + ':00' : ''
      http({
        url: http.adornUrl('/shop/giveaway'),
        method: Data.dataForm.giveawayId && Data.dataForm.giveawayId !== '0' ? 'put' : 'post',
        data: http.adornData({
          giveawayId: Data.dataForm.giveawayId || undefined,
          name: Data.dataForm.name,
          startTime: Data.dataForm.startTime,
          endTime: Data.dataForm.endTime,
          prodId: Data.dataForm.prodId,
          status: Data.dataForm.status,
          buyNum: Data.dataForm.buyNum,
          giveawayProds
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            Data.isSubmit = false
            back()
          }
        })
      }).catch(({ e }) => {
        Data.isSubmit = false
      })
      Data.dataForm.startTime = startTime
      Data.dataForm.endTime = endTime
    } else {
      Data.isSubmit = false
    }
  })
}

const prodsSelectRef = ref()
// 打开选择主商品
const addProd = () => {
  Data.prodsSelectVisible = true
  nextTick(() => {
    prodsSelectRef.value.init(Data.dataForm.prod)
  })
}
const restrictedInput = (e) => {
  const key = e.key
  // 不允许输入'e'和'.'
  if (key === 'e' || key === '.') {
    e.returnValue = false
    return false
  }
  return true
}
// 输入值校验
const inputBuyNum = (val, min, max) => {
  if (val > max) {
    Data.dataForm.buyNum = max
  }
  if (val < min || !val) {
    Data.dataForm.buyNum = min
  }
}
const deleteMainProd = () => {
  Data.dataForm.prodId = null
  Data.dataForm.buyNum = 1
}

const router = useRouter()
const back = () => {
  router.push('/marketing/giveaway/index')
}
</script>

<style lang="scss" scoped>
.page-giveaway-add-or-update {
  .coupon-input {
    width: 220px;
  }

  .form-box {
    margin-left: 40px;
  }

  .date-picker {
    display: flex;
  }

  .error-tips {
    color: #f56c6c;
    font-size: 12px;
    padding-bottom: 4px;
  }

  .prodItem-table {
    .prod-info-container {
      height: 100%;
      display: flex;
      justify-content: space-between;

      .prod-image {
        margin-right: 20px;
        width: 80px;
        height: 80px;
        flex-shrink: 0;
      }

      .prod-name {
        flex: 1;
        height: 80px;
        display: flex;
        flex-direction: column;
        text-align: start;
        justify-content: center;

        .prod-name-txt {
          font-size: 14px;
          color: #333333;
          word-break: break-all;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          line-break: anywhere;
        }
      }
    }

    // 表格输入框
    .tag-input-width {
      width: 100%;
      padding-left: 5px;
      padding-right: 0;
      border: 1px solid #DCDCDC;
      border-radius: 2px;
      height: 32px;
      line-height: 32px;
      box-sizing: border-box;

      &:focus {
        outline: 0;
      }
    }
  }

  :deep(.el-select .el-input__suffix-inner){
      display: none;
    }
  .select-time:hover :deep(.el-input__suffix-inner){
    display: inline-flex;
  }
}
</style>
